import React, { useEffect, useState } from 'react';
import {
    Card,
    Checkbox,
    Dialog,
    DialogProps, FormProps,
    MessagePlugin,
    Radio,
    Textarea,
    Switch,
    Tooltip,
    Link,
    PrimaryTable,
    Pagination,
    Message,

} from 'tdesign-react';
import { ErrorCircleFilledIcon, CheckCircleFilledIcon, CloseCircleFilledIcon } from 'tdesign-icons-react';

import axios from 'axios';
import { flushSync } from 'react-dom';

import {
    Button,
    Cascader,
    DatePicker,
    Form,
    Input,
    InputNumber,
    Mentions,
    Select,
    TreeSelect,
    Segmented,
    Space,
    Table,
    Tag,
    Modal,
    Tabs,
    Menu,
} from 'antd';

import type { PaginationProps, TableProps } from 'antd';

import { message } from 'antd';
import TabPane from 'antd/es/tabs/TabPane';
import Sider from 'antd/es/layout/Sider';
axios.defaults.baseURL = 'http://127.0.0.1:3000/zlq'


export default function Parameter() {
    const [form] = Form.useForm()

    const [visible, setVisible] = useState(false);
    // const name = Form.useWatch('name', form);
    const gender = Form.useWatch('gender', form);
    // console.log('name', name);
    console.log('gender', gender);


    const [id, setId] = useState('')
    const [can_num, setCanNum] = useState('')
    const [xi_num, setXiNum] = useState('')
    const [name, setName] = useState('')
    const [content, setContent] = useState('')
    const [state, setState] = useState('')
    const [value, setValue] = useState('A100')
    const [ren, setRen] = useState('张三')

    const getDictionary_cate = async () => {
        let { data: { code, dictionary_cateList } } = await axios.get(`/dictionary_cateList?name=${dictionary_cateName}`)
        if (code == 200) {
            setDictionary_data(dictionary_cateList)
        }
    }

    let [so_name, setSo_Name] = useState('')
    let [so_can_num, setSoCanNum] = useState('')
    let [so_state, setSoState] = useState('')

    const getParameterList = async () => {
        let { data: { code, parameterList, total } } = await axios.get(`/parameterList?page=${page}&pagesize=${pageSize}&name=${so_name}&can_num=${so_can_num}&state=${so_state}`)
        if (code == 200) {
            setTotal(total)
            setData(parameterList)
        }
    }

    let page = 1
    let pageSize = 2
    let [total, setTotal] = useState(0)

    const onChange: PaginationProps['onChange'] = (pageInfo) => {
        page = pageInfo.current
        pageSize = pageInfo.pageSize
        getParameterList()
        console.log(pageInfo);
    };
    const onPageSizeChange: PaginationProps['onPageSizeChange'] = (size) => {
        pageSize = size
        getParameterList()
        console.log('page-size:', size);
    };
    const onCurrentChange: PaginationProps['onCurrentChange'] = (index, pageInfo) => {
        page = index
        getParameterList()
        console.log(`转到第${index}页`);
        console.log(pageInfo);
    };



    const getEdit = (id: any) => {
        showModal()
        console.log(id);
        setId(id._id);
        setContent(id.content);
        setCanNum(id.can_num);
        setState(id.state);
        setName(id.name);
        setValue(id.value);
        setXiNum(id.xi_num);
        setVisible(true);
    };

    const getUpdate = async () => {
        let form = {
            _id: id,
            value: value,
            can_num: can_num,
            xi_num: xi_num,
            ren: ren,
            name: name,
            content: content,
            state: state
        }
        let { data: { code } } = await axios.post('parameterupd', form)
        if (code == 200) {
            getParameterList()
            setId('')
            setValue("")
            setXiNum("")
            setCanNum("")
            setName("")
            setContent("")
            setState("")
            handleOk()
        }
    }

    const getAdd = async () => {
        let form = {
            value: value,
            can_num: can_num,
            xi_num: xi_num,
            ren: ren,
            name: name,
            content: content,
            state: state
        }

        let { data: { code } } = await axios.post('parameteradd', form)
        if (code == 200) {
            getParameterList()
            setId('')
            setValue("")
            setXiNum("")
            setCanNum("")
            setName("")
            setContent("")
            setState("")
            handleOk()
        }
    }

    const [messageApi, contextHolder] = message.useMessage();

    //词条删除
    const getDel = async (id) => {
        let { data: { code } } = await axios.delete(`parameterdel?_id=${id}`)
        if (code == 200) {
            getParameterList()
        }
    }

    const variant = Form.useWatch('variant', form);

    // 提交表单时的操作
    const onFinish = (values) => {
        console.log(values);
        // 你可以在这里发送这些数据到后台
    };

    interface DataType {
        key: string;
        name: string;
        num: number;
        address: string;
        tags: string[];
    }

    //词条表格
    const columns: TableProps<DataType>['columns'] = [
        {
            title: '参数编码',
            dataIndex: 'can_num',
            key: 'can_num',
            render: (text) => <a>{text}</a>,
        },
        {
            title: '参数名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '参数说明',
            dataIndex: 'content',
            key: 'content',
        },
        {
            title: '参数值',
            dataIndex: 'value',
            key: 'value',
        },
        {
            title: '状态',
            key: 'tags',
            dataIndex: 'tags',
            render: (_, row) => (
                <Space size="middle">
                    {row.state ? (
                        <p style={{ color: "green" }}>启用</p>
                    ) : (
                        <p style={{ color: "red" }}>禁用</p>
                    )}
                </Space>
            ),
        },
        {
            title: '归属系统编码',
            dataIndex: 'xi_num',
            key: 'xi_num',
        }, {
            title: '创建人',
            dataIndex: 'ren',
            key: 'ren',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <a onClick={() => { getEdit(record) }}>编辑</a>
                    <a style={{ color: "red" }} onClick={() => { getDel(record._id) }}>删除</a>
                </Space>
            ),
        },
    ];

    const [data, setData] = useState<DataType[]>([]);

    //词条回显
    useEffect(() => {
        form.setFieldsValue({
            value: value,
            can_num: can_num,
            xi_num: xi_num,
            ren: ren,
            name: name,
            content: content,
            state: state
        });
    }, [name, can_num, xi_num, content, ren, state]);

    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const onSelectChange = (newSelectedRowKeys) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };


    //新增词条弹框
    const [isModalOpen, setIsModalOpen] = useState(false);

    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleOk = () => {
        setValue("")
        setXiNum("")
        setCanNum("")
        setName("")
        setContent("")
        setState("")
        setRen("")
        setIsModalOpen(false);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };

    const { TabPane } = Tabs;

    //词条权限分类
    // 用来存储当前选中的分类
    const [selectedCategory, setSelectedCategory] = useState('category1');
    // 用来存储搜索的关键字
    const [searchQuery, setSearchQuery] = useState('');
    // 存储各个分类的搜索选项
    const [selectedOption, setSelectedOption] = useState(null);


    // 处理分类选择
    const handleCategoryChange = (key) => {
        setSelectedCategory(key);
        setSearchQuery('');  // 切换分类时清空搜索框
        setSelectedOption(null);  // 清空已选选项
    };

    const getGroupingAdd = async () => {
        let form = {
            name: dictionary_cateName,
        }
        let { data: { code } } = await axios.post('groupingadd', form)
        if (code == 200) {
            getDictionary_cate()
            setDictionary_cateName('')
        }
    }

    const grouping_columns: TableProps<DataType>['columns'] = [
        {
            title: '分组名称',
            dataIndex: 'name',
            key: 'name',
        },
    ];

    const [dictionary_data, setDictionary_data] = useState<DataType[]>([]);
    const [dictionary_cateName, setDictionary_cateName] = useState('')
    const [dictionary_cate_id, setDictionary_cate_id] = useState('')

    const getGroupingEdit = (id) => {
        setDictionary_cate_id(id._id)
        setDictionary_cateName(id.name)
    }

    const Dictionary_cateSo = async (e) => {
        if (e.key === 'Enter') {  // 判断是否是回车键
            console.log('回车键被按下，执行搜索');
            // 在这里触发搜索逻辑
            // 例如，调用一个搜索 API，或者根据 so_name 进行搜索
            getDictionary_cate()
        }
    }

    const getDictionary_cateDel = async (id) => {
        let { data: { code } } = await axios.delete(`dictionary_catedel?_id=${id}`)
        if (code == 200) {
            getDictionary_cate()
        }
    }

    let [indexs, setIndexs] = useState('')
    // 分类搜索
    const handleCategoryClick = (e) => {
        if (indexs = e._id) {
            setIndexs(e._id)
            getParameterList()
        }
        console.log(indexs);
    };
    const [filteredData, setFilteredData] = useState(data);
    const [authority, setAuthority] = useState('')
    let [optionList, setOptionList] = useState([
        { id: 1, name: false, value: "禁用" }, { id: 2, name: true, value: "启用" }
    ])

    const getSo = () => {
        getParameterList();
    };

    useEffect(() => {
        getDictionary_cate()
        getParameterList()
    }, [])
    return (
        <div>
            <div style={{ marginRight: "20px", }}>
                <Card bordered style={{width: "1000px",marginBottom:"10px"}}>
                    <div style={{ display: 'flex'}}>
                        <Form.Item label="字典名称" name="so_name" initialValue={so_name} style={{ marginRight: "10px" }}>
                            <Input
                                value={so_name}
                                onChange={(e) => setSo_Name(e.target.value)}  // 更新输入框的值
                            />
                        </Form.Item>
                        <Form.Item label="参数编码" name="so_can_num" initialValue={so_name} style={{ marginRight: "10px" }}>
                            <Input
                                value={so_name}
                                onChange={(e) => setSoCanNum(e.target.value)}  // 更新输入框的值
                            />
                        </Form.Item>
                        <Form.Item label="状态" name="so_college" initialValue={authority} style={{ marginRight: "10px" }}>
                            <Select clearable value={so_state} placeholder='全部状态' onChange={(value: string) => { setSoState(value) }}>
                                {optionList.map((item, index) => (
                                    <Select.Option key={index} value={item.name}>
                                        {item.value}
                                    </Select.Option>
                                ))}
                            </Select>
                        </Form.Item>
                        <Button style={{marginLeft:"50px"}} type="primary" htmlType="submit" onClick={() => { getSo() }}>
                            搜索
                        </Button>
                    </div>
                </Card>
            </div>

            <div style={{ height: "500px" }}>
                <Card
                    bordered
                    headerBordered
                    style={{ height: "600px", width: "1000px" }}
                >
                    <div style={{ marginBottom: "50px" }}>
                        <Button style={{ float: "right" }} onClick={showModal}>新增词条</Button>
                    </div>
                    <Modal title="编辑词条" closable={false} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} footer={null}>
                        <div style={{ maxWidth: 600 }}>
                            <Form
                                form={form}
                                variant={variant || 'filled'}
                                initialValues={{
                                    variant: 'filled',
                                    id: id,
                                    value: value,
                                    can_num: can_num,
                                    xi_num: xi_num,
                                    name: name,
                                    ren: ren,
                                    content: content,
                                    state: state
                                }}
                                onFinish={onFinish}
                            >
                                {/* entry 字段 */}
                                <Form.Item
                                    label="参数编码"
                                    name="can_num"
                                    rules={[{ required: true, message: 'Please input Entry!' }]}
                                >
                                    <Input value={can_num} onChange={(e) => setCanNum(e.target.value)} />
                                </Form.Item>
                                <Form.Item
                                    label="参数值"
                                    name="xi_num"
                                    rules={[{ required: true, message: 'Please input Entry!' }]}
                                >
                                    <Input value={xi_num} onChange={(e) => setXiNum(e.target.value)} />
                                </Form.Item>

                                {/* name 字段 */}
                                <Form.Item
                                    label="参数名称"
                                    name="name"
                                    rules={[{ required: true, message: 'Please input Name!' }]}
                                >
                                    <Input value={name} onChange={(e) => setName(e.target.value)} />
                                </Form.Item>
                                {/* state 字段 */}
                                <Form.Item label="状态" name="state">
                                    <Radio.Group onChange={(e) => setState(e)} value={state}>
                                        <Radio value={true}>启用</Radio>
                                        <Radio value={false}>禁用</Radio>
                                    </Radio.Group>
                                </Form.Item>
                                {/* content 字段 */}
                                <Form.Item
                                    label="参数说明"
                                    name="content"
                                    rules={[{ required: true, message: 'Please input Content!' }]}
                                >
                                    <Input rows={5} value={content} onChange={(e) => setContent(e.target.value)} />
                                </Form.Item>


                                <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
                                    {
                                        id ? <Button type="primary" htmlType="submit" onClick={() => { getUpdate() }}>
                                            编辑
                                        </Button> :
                                            <Button type="primary" htmlType="submit" onClick={() => { getAdd() }}>
                                                新增
                                            </Button>
                                    }
                                    <Button type="primary" htmlType="submit" onClick={() => { handleOk() }}>
                                        取消
                                    </Button>
                                </Form.Item>
                            </Form>
                        </div>
                    </Modal>
                    <div>
                        <Table<DataType> pagination={false} rowSelection={rowSelection} columns={columns} dataSource={data} />
                    </div>
                    <Pagination
                        total={total}
                        defaultPageSize={pageSize}
                        onChange={onChange}
                        onCurrentChange={onCurrentChange}
                        onPageSizeChange={onPageSizeChange}
                    />
                </Card>
            </div >
        </div >
    );
}